﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using DAL;

namespace UI
{
    public partial class themsanphamvaogio : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Session["TenDN"] != null)
                {
                    if (Request.QueryString["MaSP"] != null)
                    {
                        ThemSPVaoGioHang();
                        Response.Redirect(Request.UrlReferrer.ToString());
                    }
                    else
                    {
                        Response.Redirect("thongbaoloi.aspx?ID=2");
                    }
                }
                else
                {
                    Response.Redirect("thongbaoloi.aspx?ID=3");
                }
            }
        }
        private void ThemSPVaoGioHang()
        {
            string MaSP = Request.QueryString["MaSP"].ToString();

            SqlParameter[] thamso = new SqlParameter[]
            {
                new SqlParameter("@MaSP",MaSP),
           
            };
            // get Sach By MaSach
            DataTable dt = DBConnection.GetDatatableByStoreProcedureName("sp_getSanPhambyMaSP", thamso);
            string tensp = dt.Rows[0]["TenSP"].ToString();
            int dongia = int.Parse(dt.Rows[0]["DonGia"].ToString());
            string hinh = "images/" + dt.Rows[0]["Image1"].ToString();
            DataTable gioHang = (DataTable)Session["GioHang"];
            // Kiem tra san pham da ton tai trong gio hang hay chua?
            int kt = 0;
            for (int i = 0; i < gioHang.Rows.Count; i++)
            {
                string temp = gioHang.Rows[i][0].ToString();
                if (temp == MaSP)
                {
                    kt = 1;
                    int slHienTai = int.Parse(gioHang.Rows[i]["soluong"].ToString());
                    gioHang.Rows[i]["soluong"] = slHienTai + 1;
                    break;
                }
            }
            if (kt == 0)
            {
                DataRow dr = gioHang.NewRow();
                dr["maSP"] = MaSP;
                dr["hinh"] = hinh;
                dr["tenhang"] = tensp;
                dr["dongia"] = dongia;
                dr["soluong"] = 1;
                gioHang.Rows.Add(dr);
                Session["GioHang"] = gioHang;
                Session["MaSach"] = MaSP;
            }
            Response.Redirect("thongbaomuahang.aspx");
        }
    }
}